package com.voute.View.Activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baoyz.actionsheet.ActionSheet;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.utils.SocializeUtils;
import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Model.Action.StartRefreshTagsAction;
import com.voute.Model.Bean.CircleDetailsInfoBean;
import com.voute.Model.Bean.DiscoveryBean;
import com.voute.Model.Bean.DiscoveryFeed;
import com.voute.Presenter.ICircleDetailsPresenter;
import com.voute.Presenter.Impl.CircleDetailPresenterImpl;
import com.voute.R;
import com.voute.View.Adapter.SimpleFeedAdapter;
import com.voute.View.IView.ICircleView;
import com.voute.Widget.CenterAlignImageSpan;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * Created by xianke on 23/04/2017.
 */

public class CircleActivity extends BaseActivity implements ICircleView {

    @BindView(R.id.back_layout)
    RelativeLayout back_layout;
    @BindView(R.id.imv_share)
    ImageView imv_share;
    @BindView(R.id.imv_report)
    ImageView imv_report;
    @BindView(R.id.tv_circle_title)
    TextView tv_circle_title;
    @BindView(R.id.tv_join_circle)
    TextView tv_join_circle;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipe_refresh_layout;
    @BindView(R.id.content_list)
    ListView content_list;

    private LinearLayout wechat_circle_layout_share;
    private LinearLayout we_chat_layout_share;
    private LinearLayout weibo_layout_share;
    private LinearLayout QQ_layout_share;
    private LinearLayout close_dialog_layout_share_share;

    private static final String KEY_CIRCLE_TITLE = "KEY_CIRCLE_TITLE";
    private static final String KEY_CIRCLE_HASH = "KEY_CIRCLE_HASH";
    private String title = "";
    private String hash = "";
    private View view_share_dialog;

    private String anchor = "0";
    private boolean stopLoadMore;
    private boolean isLoading;
    private boolean isRefresh = true;

    private ICircleDetailsPresenter presenter;
    private SimpleFeedAdapter adapter;
    private List<DiscoveryFeed> entities = new ArrayList<>();
    private CircleDetailsInfoBean circleDetailsInfo;

    private Dialog share_dialog;
    private View.OnClickListener share_listener;
    private UMImage imageurl;
    private MaterialDialog progressDialog;

    private TextView tv_share_title_unvoted;

    private Animation sacle_animation;

    private boolean isMlink=false;

    private String key_circle_mw;

    private UMShareListener shareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA share_media) {
            SocializeUtils.safeShowDialog(progressDialog);
        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            Toast.makeText(CircleActivity.this,"成功了",Toast.LENGTH_LONG).show();
            SocializeUtils.safeCloseDialog(progressDialog);
            if (share_dialog != null) {
                if (share_dialog.isShowing()) {
                    share_dialog.dismiss();
                }
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            SocializeUtils.safeCloseDialog(progressDialog);
            Toast.makeText(CircleActivity.this, "分享失败" + throwable.getMessage(), Toast.LENGTH_LONG).show();
            if (share_dialog != null) {
                if (share_dialog.isShowing()) {
                    share_dialog.dismiss();
                }
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            SocializeUtils.safeCloseDialog(progressDialog);
            Toast.makeText(CircleActivity.this, "分享取消了", Toast.LENGTH_LONG).show();
            if (share_dialog != null) {
                if (share_dialog.isShowing()) {
                    share_dialog.dismiss();
                }
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_circle;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        //获取一张图片
        Drawable drawable = getResources().getDrawable(R.mipmap.adapter_circle);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        title = getIntent().getStringExtra(KEY_CIRCLE_TITLE);
        hash = getIntent().getStringExtra(KEY_CIRCLE_HASH);
        isMlink=getIntent().getBooleanExtra("mlink",false);
        //通过intent方式获取动态参数值
        Intent intent_mw = getIntent();
        if (intent_mw != null) {
            key_circle_mw = intent_mw.getStringExtra("cid");
            Logger.i(key_circle_mw);
        }
        if(!TextUtils.isEmpty(key_circle_mw)){
            hash=key_circle_mw;
        }
        if (TextUtils.isEmpty(hash)) {
            App.GetInstance().finishActivity(CircleActivity.this);
        }
        if(!TextUtils.isEmpty(title)){
            SpannableString sp = new SpannableString("  " + title);
            //普通imageSpan 做对比
            CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
            sp.setSpan(imageSpan, 0, 1, ImageSpan.ALIGN_BASELINE);
            tv_circle_title.setText(sp);
        }
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isMlink){
                    Intent intent = new Intent(CircleActivity.this, MainActivity.class);
                    startActivity(intent);
                }
                App.GetInstance().finishActivity(CircleActivity.this);
            }
        });
        tv_join_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        swipe_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                getPagedFeedsInnerCircle();
            }
        });
        content_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int last_visiable = absListView.getLastVisiblePosition();
                if (!stopLoadMore && !isLoading && (last_visiable > 0)) {
                    if (last_visiable + 2 > totalItemCount) {
                        isRefresh = false;
                        getPagedFeedsInnerCircle();
                    }
                }
            }
        });
        presenter = new CircleDetailPresenterImpl(this, this);
        adapter = new SimpleFeedAdapter(entities, this);
        content_list.setAdapter(adapter);
        view_share_dialog = View.inflate(CircleActivity.this, R.layout.dialog_share_layout_share, null);
        progressDialog = new MaterialDialog.Builder(this)
                .progress(true, 0)
                .title("提示")
                .content("请等待...")
                .autoDismiss(false)
                .cancelable(true)
                .build();
        /**
         * 分享Dialog
         */
        share_listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id = view.getId();
                String share_url = circleDetailsInfo.getData().getCircle().getShare().getLink();
                imageurl = new UMImage(CircleActivity.this, circleDetailsInfo.getData().getCircle().getShare().getPic());
                imageurl.setThumb(new UMImage(CircleActivity.this, circleDetailsInfo.getData().getCircle().getShare().getPic()));
                imageurl.setTitle(circleDetailsInfo.getData().getCircle().getShare().getTitle());
                imageurl.setDescription(circleDetailsInfo.getData().getCircle().getShare().getDesc());


                UMWeb uweb_local = new UMWeb(share_url);
                uweb_local.setTitle(circleDetailsInfo.getData().getCircle().getShare().getTitle());
                uweb_local.setThumb(imageurl);
                uweb_local.setDescription(circleDetailsInfo.getData().getCircle().getShare().getDesc());





                switch (id) {
                    case R.id.wechat_circle_layout_share:
                        new ShareAction(CircleActivity.this)
                                .withText(circleDetailsInfo.getData().getCircle().getShare().getTitle())
                                .withMedia(uweb_local)
//                                .withTargetUrl(share_url)
//                                .withTitle(circleDetailsInfo.getData().getCircle().getShare().getName())
                                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE.toSnsPlatform().mPlatform)
                                .setCallback(shareListener).share();
                        break;
                    case R.id.we_chat_layout_share:
                        new ShareAction(CircleActivity.this)
                                .withText(circleDetailsInfo.getData().getCircle().getShare().getTitle())
                                .withMedia(uweb_local)
//                                .withTargetUrl(share_url)
//                                .withTitle(circleDetailsInfo.getData().getCircle().getShare().getName())
                                .setPlatform(SHARE_MEDIA.WEIXIN.toSnsPlatform().mPlatform)
                                .setCallback(shareListener).share();
                        break;
                    case R.id.weibo_layout_share:
                        new ShareAction(CircleActivity.this)
                                .withText(circleDetailsInfo.getData().getCircle().getShare().getTitle())
                                .withMedia(uweb_local)
//                                .withTargetUrl(share_url)
//                                .withTitle(circleDetailsInfo.getData().getCircle().getShare().getName())
                                .setPlatform(SHARE_MEDIA.SINA.toSnsPlatform().mPlatform)
                                .setCallback(shareListener).share();
                        break;
                    case R.id.QQ_layout_share:
                        new ShareAction(CircleActivity.this)
                                .withText(circleDetailsInfo.getData().getCircle().getShare().getTitle())
                                .withMedia(uweb_local)
//                                .withTargetUrl(share_url)
//                                .withTitle(circleDetailsInfo.getData().getCircle().getShare().getName())
                                .setPlatform(SHARE_MEDIA.QQ.toSnsPlatform().mPlatform)
                                .setCallback(shareListener).share();
                        break;
                }
            }
        };
        wechat_circle_layout_share = (LinearLayout) view_share_dialog.findViewById(R.id.wechat_circle_layout_share);
        we_chat_layout_share = (LinearLayout) view_share_dialog.findViewById(R.id.we_chat_layout_share);
        weibo_layout_share = (LinearLayout) view_share_dialog.findViewById(R.id.weibo_layout_share);
        QQ_layout_share = (LinearLayout) view_share_dialog.findViewById(R.id.QQ_layout_share);
        tv_share_title_unvoted=(TextView) view_share_dialog.findViewById(R.id.tv_share_title_unvoted);
        close_dialog_layout_share_share = (LinearLayout) view_share_dialog.findViewById(R.id.close_dialog_layout_share_share);
        wechat_circle_layout_share.setOnClickListener(share_listener);
        we_chat_layout_share.setOnClickListener(share_listener);
        weibo_layout_share.setOnClickListener(share_listener);
        QQ_layout_share.setOnClickListener(share_listener);
        close_dialog_layout_share_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                share_dialog.dismiss();
            }
        });


        imv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (share_dialog == null) {
                    initShareDialog();
                }
                tv_share_title_unvoted.setText("分享，邀请好友加入这个圈子");
                share_dialog.show();
            }
        });
        imv_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActionSheet.createBuilder(CircleActivity.this, getSupportFragmentManager())
                        .setCancelButtonTitle("取消")
                        .setOtherButtonTitles("举报")
                        .setCancelableOnTouchOutside(true)
                        .setListener(new ActionSheet.ActionSheetListener() {
                            @Override
                            public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                            }

                            @Override
                            public void onOtherButtonClick(ActionSheet actionSheet, int which) {
                                if (which == 0) {
                                }
                            }
                        }).show();
            }
        });
        sacle_animation= AnimationUtils.loadAnimation(this,R.anim.scale_x_y_animation);
    }

    private void initShareDialog() {
        share_dialog = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = share_dialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        share_dialog.setCancelable(false);
        share_dialog.setContentView(view_share_dialog);
    }

    @Override
    public void setupData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        isRefresh = true;
        getPagedFeedsInnerCircle();
        presenter.requestCircleBaseInfo(hash);
        MobclickAgent.onEvent(CircleActivity.this, "view_circle");
    }

    @Override
    public void refreshCircleDetailsView(DiscoveryBean beans) {
        if (beans != null) {
            if (beans.getStatus() == 0) {
                isLoading = false;
                if (isRefresh) {
                    anchor = "0";
                    entities.clear();
                    isRefresh = false;
                }
                if (beans.getData() != null) {
                    if (beans.getData().getFeeds() != null && beans.getData().getFeeds().size() > 0) {
                        entities.addAll(beans.getData().getFeeds());
                        adapter.setData(entities);
                        stopLoadMore = false;
                    } else {
                        stopLoadMore = true;
                    }
                } else {
                    isLoading = false;
                    stopLoadMore = false;
                }
            } else {
                isLoading = false;
                stopLoadMore = false;
            }
        } else {
            isLoading = false;
            stopLoadMore = false;
        }
    }

    @Override
    public void setCircleBaseInfo(CircleDetailsInfoBean response) {
        circleDetailsInfo = response;

        SpannableString sp = new SpannableString("  " + response.getData().getCircle().getName());
        //获取一张图片
        Drawable drawable = getResources().getDrawable(R.mipmap.adapter_circle);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        //普通imageSpan 做对比
        CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
        sp.setSpan(imageSpan, 0, 1, ImageSpan.ALIGN_BASELINE);
        tv_circle_title.setText(sp);
        tv_join_circle.setVisibility(View.VISIBLE);
        if (circleDetailsInfo.getData().getCircle().isJoined()) {
            tv_join_circle.setBackgroundResource(R.drawable.bg_joined_circle);
            tv_join_circle.setTextColor(Color.parseColor("#999999"));
            tv_join_circle.setText("已加入");
            tv_join_circle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new MaterialDialog.Builder(CircleActivity.this).title("提示").positiveText("确定").negativeText("取消").content("退出此圈子?").onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            presenter.ExitCircle(hash);
                        }
                    }).show();
                }
            });
        } else {
            tv_join_circle.setBackgroundResource(R.drawable.bg_join_circle);
            tv_join_circle.setTextColor(Color.parseColor("#fe3768"));
            tv_join_circle.setText("+  加入");

            sacle_animation.setAnimationListener(new RepeatAnimationListener());
            tv_join_circle.startAnimation(sacle_animation);
            sacle_animation.startNow();

            tv_join_circle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (checkLoginStatus()) {
                        presenter.JoinCircle(hash);
                    }
                }
            });
        }
    }

    @Override
    public void joinCircleSuccess() {
        tv_join_circle.setBackgroundResource(R.drawable.bg_joined_circle);
        tv_join_circle.setTextColor(Color.parseColor("#999999"));
        tv_join_circle.setText("已加入");
        tv_join_circle.setClickable(false);
        tv_join_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MaterialDialog.Builder(CircleActivity.this).title("提示").positiveText("确定").negativeText("取消").content("退出此圈子?").onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        presenter.ExitCircle(hash);
                    }
                }).show();
            }
        });
        StartRefreshTagsAction action=new StartRefreshTagsAction();
        EventBus.getDefault().post(action);
        tv_join_circle.clearAnimation();
    }

    @Override
    public void onBackPressed() {
        if(isMlink){
            Intent intent = new Intent(CircleActivity.this, MainActivity.class);
            startActivity(intent);
        }
        App.GetInstance().finishActivity(CircleActivity.this);
    }

    @Override
    public void exitCircleSuccess() {
        tv_join_circle.setBackgroundResource(R.drawable.bg_join_circle);
        tv_join_circle.setTextColor(Color.parseColor("#fe3768"));
        tv_join_circle.setText("+  加入");


        sacle_animation.setAnimationListener(new RepeatAnimationListener());
        tv_join_circle.startAnimation(sacle_animation);
        sacle_animation.startNow();



        tv_join_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.JoinCircle(hash);
            }
        });
        StartRefreshTagsAction action=new StartRefreshTagsAction();
        EventBus.getDefault().post(action);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {
        swipe_refresh_layout.setRefreshing(false);
    }

    @Override
    public void showError(String errMsg) {
        MaterialDialog notice_dialog = new MaterialDialog.Builder(this).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }

    private void getPagedFeedsInnerCircle() {
        String anchor = "0";
        if (isRefresh)
            anchor = "0";
        else {
            if (entities.size() == 0) {
                anchor = "0";
            } else {
                anchor = entities.get(entities.size() - 1).getId() + "";
            }
        }
        if (!isRefresh) {
            if (stopLoadMore) {
                return;
            } else {
                stopLoadMore = true;
                isLoading = true;
            }
        } else {
            isLoading = true;
            stopLoadMore = true;
        }
        presenter.requestCircleDetails(hash, anchor);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        UMShareAPI.get(this).release();
        super.onDestroy();
    }

    public class RepeatAnimationListener implements Animation.AnimationListener{

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            animation.reset();
            animation.setAnimationListener(new RepeatAnimationListener());
            animation.start();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    }
}
